<template>
  <div class="expansion-results">
    <div class="results-header">
      <div class="results-title">
        <el-icon><PictureFilled /></el-icon>
        扩展结果 ({{ expandedImages.length }})
      </div>
      <div class="results-actions">
        <el-button 
          v-if="selectedImages.length > 0"
          type="primary"
          :icon="Download"
          @click="downloadSelected"
        >
          下载选中 ({{ selectedImages.length }})
        </el-button>
        <el-button 
          v-if="selectedImages.length > 0"
          type="success"
          :icon="DocumentAdd"
          @click="composeSelected"
        >
          图文组合
        </el-button>
        <el-button 
          text
          size="small"
          @click="clearAllResults"
          v-if="expandedImages.length > 0"
        >
          清空所有
        </el-button>
      </div>
    </div>
    
    <!-- 视图控制 -->
    <div class="view-controls">
      <div class="view-options">
        <el-radio-group v-model="viewMode" size="small">
          <el-radio-button label="grid">
            <el-icon><Grid /></el-icon>
            网格视图
          </el-radio-button>
          <el-radio-button label="compare">
            <el-icon><Rank /></el-icon>
            对比视图
          </el-radio-button>
        </el-radio-group>
      </div>
      
      <div class="sort-options">
        <el-select v-model="sortBy" size="small" @change="handleSort">
          <el-option label="生成时间" value="createdAt" />
          <el-option label="相似度" value="similarity" />
          <el-option label="质量评分" value="quality" />
        </el-select>
      </div>
    </div>
    
    <!-- 网格视图 -->
    <div v-if="viewMode === 'grid'" class="results-grid">
      <div
        v-for="(image, index) in sortedImages"
        :key="image.id || index"
        class="result-item"
        :class="{ 'selected': isSelected(image) }"
        @click="toggleSelection(image)"
      >
        <div class="image-container">
          <img 
            :src="image.generatedImageUrl || image.tempUrl" 
            :alt="`扩展图片 ${index + 1}`"
            class="result-image"
            @load="handleImageLoad"
          />
          
          <!-- 选择指示器 -->
          <div class="selection-indicator" v-if="isSelected(image)">
            <el-icon><Check /></el-icon>
          </div>
          
          <!-- 图片操作 -->
          <div class="image-overlay">
            <div class="image-actions">
              <el-button 
                type="primary" 
                :icon="View" 
                circle 
                size="small"
                @click.stop="previewImage(image)"
              />
              <el-button 
                type="success" 
                :icon="Download" 
                circle 
                size="small"
                @click.stop="downloadImage(image)"
              />
              <el-button 
                type="info" 
                :icon="Share" 
                circle 
                size="small"
                @click.stop="shareImage(image)"
              />
              <el-button 
                type="danger" 
                :icon="Delete" 
                circle 
                size="small"
                @click.stop="deleteImage(image, index)"
              />
            </div>
          </div>
          
          <!-- 生成状态 -->
          <div class="generation-status" :class="getStatusClass(image.aiGenerationStatus)">
            {{ getStatusText(image.aiGenerationStatus) }}
          </div>
        </div>
        
        <div class="image-info">
          <div class="image-meta">
            <div class="meta-row">
              <span class="meta-label">相似度:</span>
              <div class="similarity-bar">
                <el-progress 
                  :percentage="Math.round((image.similarityScore || 0) * 100)" 
                  :show-text="false"
                  :stroke-width="4"
                />
                <span class="similarity-text">{{ Math.round((image.similarityScore || 0) * 100) }}%</span>
              </div>
            </div>
            
            <div class="meta-row">
              <span class="meta-label">生成时间:</span>
              <span class="meta-value">{{ formatTime(image.createdAt) }}</span>
            </div>
            
            <div class="meta-row" v-if="image.generationParams">
              <span class="meta-label">风格:</span>
              <el-tag size="small">{{ getStyleFromParams(image.generationParams) }}</el-tag>
            </div>
          </div>
          
          <div class="image-actions-bottom">
            <el-button 
              type="primary" 
              size="small"
              @click.stop="useAsTemplate(image)"
            >
              用作模板
            </el-button>
            <el-button 
              type="success" 
              size="small"
              @click.stop="generateMore(image)"
            >
              生成更多
            </el-button>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 对比视图 -->
    <div v-else-if="viewMode === 'compare'" class="compare-view">
      <div class="compare-container">
        <!-- 原图 -->
        <div class="compare-item original">
          <div class="compare-header">
            <h4>原图</h4>
          </div>
          <div class="compare-image-container">
            <img 
              :src="originalImage?.fileUrl" 
              :alt="originalImage?.originalName"
              class="compare-image"
            />
          </div>
          <div class="compare-info">
            <div class="info-item">
              <span>尺寸: {{ originalImage?.width }}×{{ originalImage?.height }}</span>
            </div>
            <div class="info-item">
              <span>大小: {{ formatFileSize(originalImage?.fileSize || 0) }}</span>
            </div>
          </div>
        </div>
        
        <!-- 扩展图片 -->
        <div 
          v-for="(image, index) in sortedImages.slice(0, 3)"
          :key="image.id || index"
          class="compare-item expanded"
        >
          <div class="compare-header">
            <h4>扩展图 {{ index + 1 }}</h4>
            <div class="compare-actions">
              <el-button 
                type="primary" 
                :icon="Check"
                size="small"
                @click="selectBest(image)"
              >
                选为最佳
              </el-button>
            </div>
          </div>
          <div class="compare-image-container">
            <img 
              :src="image.generatedImageUrl || image.tempUrl" 
              :alt="`扩展图片 ${index + 1}`"
              class="compare-image"
            />
          </div>
          <div class="compare-info">
            <div class="info-item">
              <span>相似度: {{ Math.round((image.similarityScore || 0) * 100) }}%</span>
            </div>
            <div class="info-item">
              <span>状态: {{ getStatusText(image.aiGenerationStatus) }}</span>
            </div>
            <div class="info-item" v-if="image.generationParams">
              <span>风格: {{ getStyleFromParams(image.generationParams) }}</span>
            </div>
          </div>
        </div>
      </div>
    </div>
    
    <!-- 空状态 -->
    <div v-if="expandedImages.length === 0 && !loading" class="empty-results">
      <el-icon size="64" color="rgba(255,255,255,0.5)"><Picture /></el-icon>
      <h3>暂无扩展结果</h3>
      <p>开始图片扩展后，生成的图片将在这里显示</p>
    </div>
    
    <!-- 加载状态 -->
    <div v-if="loading" class="loading-results">
      <el-icon class="loading-icon"><Loading /></el-icon>
      <p>正在生成扩展图片...</p>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import {
  PictureFilled, Download, DocumentAdd, Grid, Rank, Check, View, Share, Delete,
  Picture, Loading
} from '@element-plus/icons-vue'
import type { ImageModel, GeneratedImageModel } from '@/types'
import { formatTime, formatFileSize, downloadFile } from '@/utils'

interface Props {
  expandedImages: GeneratedImageModel[]
  originalImage?: ImageModel
  loading?: boolean
}

interface Emits {
  (e: 'preview', image: GeneratedImageModel): void
  (e: 'download', image: GeneratedImageModel): void
  (e: 'share', image: GeneratedImageModel): void
  (e: 'delete', image: GeneratedImageModel, index: number): void
  (e: 'use-template', image: GeneratedImageModel): void
  (e: 'generate-more', image: GeneratedImageModel): void
  (e: 'compose', images: GeneratedImageModel[]): void
  (e: 'select-best', image: GeneratedImageModel): void
}

const props = defineProps<Props>()
const emit = defineEmits<Emits>()

// 响应式数据
const viewMode = ref<'grid' | 'compare'>('grid')
const sortBy = ref('createdAt')
const selectedImages = ref<GeneratedImageModel[]>([])

// 计算属性
const sortedImages = computed(() => {
  const images = [...props.expandedImages]
  
  switch (sortBy.value) {
    case 'similarity':
      return images.sort((a, b) => (b.similarityScore || 0) - (a.similarityScore || 0))
    case 'quality':
      // 假设有质量评分字段
      return images.sort((a, b) => (b as any).qualityScore - (a as any).qualityScore)
    case 'createdAt':
    default:
      return images.sort((a, b) => new Date(b.createdAt).getTime() - new Date(a.createdAt).getTime())
  }
})

// 方法
const isSelected = (image: GeneratedImageModel) => {
  return selectedImages.value.some(selected => selected.id === image.id)
}

const toggleSelection = (image: GeneratedImageModel) => {
  const index = selectedImages.value.findIndex(selected => selected.id === image.id)
  if (index > -1) {
    selectedImages.value.splice(index, 1)
  } else {
    selectedImages.value.push(image)
  }
}

const handleSort = () => {
  // 排序已通过计算属性处理
}

const previewImage = (image: GeneratedImageModel) => {
  emit('preview', image)
}

const downloadImage = (image: GeneratedImageModel) => {
  emit('download', image)
}

const shareImage = (image: GeneratedImageModel) => {
  emit('share', image)
}

const deleteImage = async (image: GeneratedImageModel, index: number) => {
  try {
    await ElMessageBox.confirm('确定要删除这张扩展图片吗？', '确认删除', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    emit('delete', image, index)
  } catch {
    // 用户取消
  }
}

const useAsTemplate = (image: GeneratedImageModel) => {
  emit('use-template', image)
}

const generateMore = (image: GeneratedImageModel) => {
  emit('generate-more', image)
}

const downloadSelected = () => {
  if (selectedImages.value.length === 0) return
  
  selectedImages.value.forEach(image => {
    if (image.generatedImageUrl) {
      downloadFile(image.generatedImageUrl, `扩展图片_${image.id}.jpg`)
    }
  })
  
  ElMessage.success(`开始下载 ${selectedImages.value.length} 张图片`)
}

const composeSelected = () => {
  if (selectedImages.value.length === 0) return
  emit('compose', selectedImages.value)
}

const selectBest = (image: GeneratedImageModel) => {
  emit('select-best', image)
  ElMessage.success('已选择为最佳扩展图片')
}

const clearAllResults = async () => {
  try {
    await ElMessageBox.confirm('确定要清空所有扩展结果吗？', '确认清空', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })
    
    // 清空所有结果的逻辑由父组件处理
    selectedImages.value = []
  } catch {
    // 用户取消
  }
}

const handleImageLoad = (event: Event) => {
  const img = event.target as HTMLImageElement
  img.classList.add('loaded')
}

const getStatusClass = (status: string) => {
  switch (status) {
    case 'SUCCESS': return 'status-success'
    case 'FAILED': return 'status-failed'
    default: return 'status-pending'
  }
}

const getStatusText = (status: string) => {
  switch (status) {
    case 'SUCCESS': return '生成成功'
    case 'FAILED': return '生成失败'
    default: return '生成中'
  }
}

const getStyleFromParams = (params: string) => {
  try {
    const config = JSON.parse(params || '{}')
    switch (config.style) {
      case 'similar': return '相似风格'
      case 'artistic': return '艺术风格'
      case 'realistic': return '写实风格'
      case 'cartoon': return '卡通风格'
      case 'vintage': return '复古风格'
      case 'modern': return '现代风格'
      default: return '未知风格'
    }
  } catch {
    return '未知风格'
  }
}
</script>

<style scoped>
.expansion-results {
  background: rgba(255, 255, 255, 0.1);
  backdrop-filter: blur(10px);
  border-radius: 20px;
  padding: 20px;
  color: white;
}

.results-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding-bottom: 15px;
  border-bottom: 1px solid rgba(255, 255, 255, 0.1);
}

.results-title {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 18px;
  font-weight: 600;
}

.results-actions {
  display: flex;
  gap: 10px;
}

.view-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 15px;
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
}

/* 网格视图样式 */
.results-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(280px, 1fr));
  gap: 20px;
}

.result-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  overflow: hidden;
  cursor: pointer;
  transition: all 0.3s ease;
}

.result-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 10px 30px rgba(0, 0, 0, 0.3);
}

.result-item.selected {
  background: rgba(64, 158, 255, 0.2);
  border: 2px solid #409EFF;
}

.image-container {
  position: relative;
  aspect-ratio: 1;
  overflow: hidden;
}

.result-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
  transition: all 0.3s ease;
  opacity: 0;
}

.result-image.loaded {
  opacity: 1;
}

.selection-indicator {
  position: absolute;
  top: 10px;
  right: 10px;
  width: 24px;
  height: 24px;
  background: #409EFF;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  color: white;
  font-size: 14px;
}

.image-overlay {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  opacity: 0;
  transition: opacity 0.3s ease;
}

.result-item:hover .image-overlay {
  opacity: 1;
}

.image-actions {
  display: flex;
  gap: 10px;
}

.generation-status {
  position: absolute;
  bottom: 10px;
  left: 10px;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-success {
  background-color: rgba(103, 194, 58, 0.8);
  color: white;
}

.status-failed {
  background-color: rgba(245, 108, 108, 0.8);
  color: white;
}

.status-pending {
  background-color: rgba(230, 162, 60, 0.8);
  color: white;
}

.image-info {
  padding: 15px;
}

.image-meta {
  margin-bottom: 15px;
}

.meta-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 8px;
}

.meta-label {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.7);
}

.meta-value {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.9);
}

.similarity-bar {
  display: flex;
  align-items: center;
  gap: 8px;
  flex: 1;
  margin-left: 10px;
}

.similarity-bar :deep(.el-progress) {
  flex: 1;
}

.similarity-text {
  font-size: 11px;
  color: rgba(255, 255, 255, 0.8);
  min-width: 35px;
}

.image-actions-bottom {
  display: flex;
  gap: 10px;
}

/* 对比视图样式 */
.compare-view {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 15px;
  padding: 20px;
}

.compare-container {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
  gap: 20px;
}

.compare-item {
  background: rgba(255, 255, 255, 0.05);
  border-radius: 10px;
  padding: 15px;
}

.compare-item.original {
  border: 2px solid rgba(64, 158, 255, 0.5);
}

.compare-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.compare-header h4 {
  margin: 0;
  font-size: 14px;
  font-weight: 500;
}

.compare-image-container {
  aspect-ratio: 1;
  border-radius: 8px;
  overflow: hidden;
  margin-bottom: 15px;
}

.compare-image {
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.compare-info {
  display: flex;
  flex-direction: column;
  gap: 5px;
}

.info-item {
  font-size: 12px;
  color: rgba(255, 255, 255, 0.8);
}

/* 空状态和加载状态 */
.empty-results,
.loading-results {
  text-align: center;
  padding: 60px 20px;
  color: rgba(255, 255, 255, 0.7);
}

.empty-results h3,
.loading-results p {
  margin: 20px 0 10px 0;
  color: white;
}

.loading-results {
  display: flex;
  flex-direction: column;
  align-items: center;
}

.loading-icon {
  font-size: 32px;
  animation: spin 1s linear infinite;
  margin-bottom: 15px;
}

@keyframes spin {
  from { transform: rotate(0deg); }
  to { transform: rotate(360deg); }
}

/* 响应式设计 */
@media (max-width: 768px) {
  .expansion-results {
    padding: 15px;
  }
  
  .results-header {
    flex-direction: column;
    gap: 15px;
  }
  
  .results-actions {
    width: 100%;
    justify-content: space-between;
  }
  
  .view-controls {
    flex-direction: column;
    gap: 15px;
  }
  
  .results-grid {
    grid-template-columns: repeat(auto-fill, minmax(200px, 1fr));
    gap: 15px;
  }
  
  .compare-container {
    grid-template-columns: 1fr;
  }
  
  .image-actions-bottom {
    flex-direction: column;
  }
}
</style>